package nps.pay.utils;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okio.Buffer;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtils {

    private static OkHttpClient client = new OkHttpClient.Builder().connectTimeout(3, TimeUnit.MINUTES).writeTimeout(3, TimeUnit.MINUTES).readTimeout(3, TimeUnit.MINUTES).build();

    /**
     * 发送请求
     *
     * @param request
     * @return
     */
    public static Response sendRequest(Request request) throws IOException {
        return client.newCall(request).execute();
    }

    /**
     * 发送post请求
     *
     * @param url
     * @param data
     * @return
     * @throws IOException
     */
    public static Response sendRequest(String url, Map<String, String> data) throws IOException {
        Request.Builder builder = new Request.Builder()
                .url(url);
        if (data != null && !data.isEmpty()) {
            Iterator<Map.Entry<String, String>> iterator = data.entrySet().iterator();
            FormBody.Builder formBody = new FormBody.Builder();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                formBody.add(entry.getKey(), entry.getValue());
            }
            builder.post(formBody.build());
        }
        Request build = builder.build();
        Buffer buffer = new Buffer();
        if (build.body() != null)
            build.body().writeTo(buffer);
        System.out.println("发送请求：  url:" + build.url() + "   body:[" + buffer.readUtf8() + "]");
        return sendRequest(build);
    }
}
